<template>
	<view class="publish-container">
		<scroll-view scroll-y class="scroll-view-content">
			<!-- 标题输入 -->
			<view class="title-input-wrapper">
				<input class="title-input" v-model="title" placeholder="添加标题，吸引更多人来互动吧~" placeholder-style="color:#ccc"
					maxlength="30" />
				<text class="char-counter">{{ title.length }}/30</text>
			</view>

			<!-- 内容输入 -->
			<view class="content-textarea-wrapper">
				<textarea class="content-textarea" v-model="content"
					placeholder="“创造一个能引起共鸣的帖子，或许能置顶成为『热门话题』哦~帖子质量越高，更能助你快速升级为『高级土著』”，快在本圈子里留下你的足迹！"
					placeholder-style="color:#ccc" auto-height :maxlength="-1" :adjust-position="false" />
			</view>

			<!-- 媒体上传 -->
			<view class="media-upload-wrapper">
				<!-- 图片上传与预览 -->
				<u-upload v-if="acceptType === 'image'" :fileList="fileList" @afterRead="handleImageUpload"
					@delete="deletePic" name="localCircleImages" multiple :maxCount="9" width="80" height="80">
				</u-upload>

				<!-- 视频预览 -->
				<view v-if="acceptType === 'video' && videoList.length > 0" class="video-preview-container">
					<video class="video-preview" :src="videoList[0].url" controls></video>
					<view class="delete-video-icon" @click="deleteVideo">
						<u-icon name="close" color="#ffffff" size="12"></u-icon>
					</view>
				</view>

				<!-- 统一上传入口，仅在未选择任何文件时显示 -->
				<view v-if="fileList.length === 0 && videoList.length === 0" class="upload-placeholder"
					@click="openUploadActionSheet">
					<u-icon name="plus" color="#d3d3d3" size="28"></u-icon>
					<text class="placeholder-text">照片/视频</text>
				</view>
			</view>

			<!-- 功能选项行 -->
			<view class="options-row">
				<view class="options-row">
					<view class="option-item" @click="onPlace">
						<u-icon name="map-fill" size="14" color="#666"></u-icon>
						<text class="option-text location-text">{{ locationInfo.name  }}</text>
					</view>
					<view class="option-item option-item-none" @click="navigateToSelectTopic">
						<u-icon name="/static/release/icon_ht.png" size="18" color="#666"></u-icon>
						<text class="option-text">添加话题</text>
						<u-icon name="play-right-fill" size="12" color="#000"></u-icon>
					</view>
				</view>
				<view class="option-item option-item-none" @click="showPowerPicker = true">
					<text class="option-text">{{ powerObject.label }}</text>
					<u-icon name="play-right-fill" size="12" color="#000"></u-icon>
				</view>
			</view>

			<!-- 已选话题展示 -->
			<view class="selected-tags-container" v-if="selectedTags.length > 0">
				<view class="tag-wrapper" v-for="(tag, index) in selectedTags" :key="tag.topicId">
					<u-tag :text="`# ${tag.title}`" shape="circle" bgColor="#FFF7E5" borderColor="#FFC22C"
						color="#8a6d3b" @click="removeTag(index)">
					</u-tag>
				</view>
			</view>
		</scroll-view>

		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<view class="draft-button">
				<u-button customStyle="color:#2E1600" shape="circle" text="存草稿" @click="saveDraft" color="#F0F0F0"
					size="large"></u-button>
			</view>

			<u-button class="publish-button" customStyle="color:#2E1600" shape="circle" text="确认发布" @click="publish"
				:loading="isSubmitting" color="#FFB427" size="large"></u-button>
		</view>

		<!-- 各种弹窗 -->
		<u-action-sheet :show="showUploadOptions" :actions="uploadActions" cancelText="取消" @select="handleUploadSelect"
			@close="showUploadOptions = false"></u-action-sheet>

		<u-popup :show="showTagPopup" @close="showTagPopup = false" mode="bottom" round="10">
			<view class="tag-popup">
				<view class="popup-header">选择话题</view>
				<scroll-view scroll-y class="tag-scroll">
					<view class="tag-list">
						<u-tag v-for="tag in availableTags" :key="tag.topicId" :text="`# ${tag.title}`"
							:plain="!isTagSelected(tag.topicId)" shape="circle"
							:bgColor="!isTagSelected(tag.topicId)?'':'#F0E8B0'" borderColor="#F0E8B0" color="#D7A441"
							@click="toggleTag(tag)" class="popup-tag-item"></u-tag>
					</view>
				</scroll-view>
				<view class="popup-footer">
					<u-button color="linear-gradient(to right, #FFD44F, #FFC53E)" shape="circle" text="完成"
						@click="showTagPopup = false"></u-button>
				</view>
			</view>
		</u-popup>

		<u-picker :show="showPowerPicker" :columns="powerColumns" keyName="label" @confirm="onConfirmPower"
			@cancel="showPowerPicker = false"></u-picker>

		<u-loading-page :loading="isUploadingGlobally" loading-text="文件上传中..."></u-loading-page>
	</view>
</template>

<script>
	import {
		getTopicsList,
		getQiniuToken,
		publishPost
	} from '@/request/api.js';
	import config from '@/config/index.js'
	// 定义常量
	const POST_IMAGE_PURPOSE = 'post_image';
	const POST_VIDEO_PURPOSE = 'post_video';

	export default {
		data() {
			return {
				title: '',
				content: '',
				fileList: [],
				videoList: [],
				acceptType: 'none', // 'none', 'image', 'video'
				isUploadingGlobally: false,
				isSubmitting: false,
				locationInfo: {},
				showTagPopup: false,
				availableTags: [],
				selectedTags: [],

				showPowerPicker: false,
				powerObject: {
					label: '公开',
					id: 1
				},
				powerColumns: [
					[{
							label: '公开',
							id: 1
						},
						{
							label: '仅朋友可见',
							id: 2
						},
						{
							label: '私密',
							id: 3
						}
					]
				],

				showUploadOptions: false,
				uploadActions: [{
						name: '从相册选择照片',
						type: 'image',
						sourceType: ['album']
					},
					{
						name: '从相册选择视频',
						type: 'video',
						sourceType: ['album']
					},
					{
						name: '拍照',
						type: 'image',
						sourceType: ['camera']
					},
					{
						name: '录像',
						type: 'video',
						sourceType: ['camera']
					}
				],

			};
		},
		onLoad() {
			this.getLocation()
			this.getTopicsList();
		},
		methods: {
			getLocation() {
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: (res) => {
						this.locationInfo = {
							province: res.address?.province || '',
							city: res.address?.city || '',
							name: res.address?.city || '未知城市',
							address: res.address?.poiName || res.address?.street || '未知地点',
							latitude: res.latitude,
							longitude: res.longitude
						};
					}
				});
			},
			getTopicsList() {
				getTopicsList({
					pageNum: 1,
					pageSize: 50
				}).then(res => {
					if (res.data && res.data.rows) {
						this.availableTags = res.data.rows.map(item => ({
							topicId: item.topicId,
							title: item.title
						}));
					}
				});
			},

			openUploadActionSheet() {
				this.showUploadOptions = true;
			},
			handleUploadSelect(action) {
				if (action.type === 'image') {
					if (this.videoList.length > 0) {
						uni.showToast({
							title: '只能上传图片或视频之一',
							icon: 'none'
						});
						return;
					}
					uni.chooseImage({
						count: 9 - this.fileList.length,
						sizeType: ['original'], // 不压缩
						sourceType: action.sourceType,
						success: (res) => this.handleImageUpload({
							file: res.tempFiles
						})
					});
				} else if (action.type === 'video') {
					if (this.fileList.length > 0) {
						uni.showToast({
							title: '只能上传图片或视频之一',
							icon: 'none'
						});
						return;
					}
					uni.chooseVideo({
						sourceType: action.sourceType,
						compressed: false, // 不压缩
						success: (res) => this.handleVideoUpload({
							file: [res]
						})
					});
				}
			},
			async handleImageUpload(event) {
				this.acceptType = 'image';
				this.isUploadingGlobally = true;
				const newFiles = event.file;
				const uploadPromises = newFiles.map(file => this.uploadSingleFile(file, true));
				await Promise.all(uploadPromises);
				this.isUploadingGlobally = false;
			},
		
			async handleVideoUpload(event) {
				this.acceptType = 'video';
				this.isUploadingGlobally = true;
				await this.uploadSingleFile(event.file[0], false);
				this.isUploadingGlobally = false;
			},
			async uploadSingleFile(file, isImage) {
				const originalName = file.name || `${isImage ? 'image' : 'video'}_${Date.now()}`;
				const purpose = isImage ? POST_IMAGE_PURPOSE : POST_VIDEO_PURPOSE;

				// 创建一个临时的占位对象
				const fileEntry = {
					url: file.path || file.url,
					status: 'uploading',
					message: '上传中...',
					originalName,
					isImage: isImage ? 1 : 0
				};

				// 立即添加到列表中以显示“上传中”状态
				if (isImage) {
					this.fileList.push(fileEntry);
				} else {
					this.videoList.push(fileEntry);
				}

				// 【修复关键点】找到刚刚添加的这个文件在数组中的索引
				const list = isImage ? this.fileList : this.videoList;
				const index = list.indexOf(fileEntry);

				try {
					const qiniuUrl = await this.uploadFileToQiniu(fileEntry.url);

					// 【修复关键点】创建一个包含所有更新信息的新对象
					const updatedFile = {
						...fileEntry, // 复制旧有属性
						url: qiniuUrl,
						status: 'success',
						message: '上传成功',
					};
					// 【修复关键点】使用 splice 替换旧对象，触发 Vue 的响应式更新
					if (index > -1) {
						list.splice(index, 1, updatedFile);
					}

				} catch (error) {
					const updatedFile = {
						...fileEntry,
						status: 'fail',
						message: '上传失败',
					};
					if (index > -1) {
						list.splice(index, 1, updatedFile);
					}
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					});
				}
			},
			
			async uploadFileToQiniu(fileUrl, purpose) {
				return new Promise((resolve, reject) => {
					const base_url = config.baseURL
					uni.uploadFile({
						url: base_url + '/qnyUpload/upload',
						filePath: fileUrl,
						name: "file",
						header: {
							'Authorization': uni.getStorageSync('token') || '',
							'Accept': 'application/json'
						},
						success: (res) => {
							// 特别检查413错误
							if (res.statusCode === 413) {
								reject(new Error('文件大小超过服务器限制，请选择较小的文件'));
								return;
							}
							try {
								// 解析服务器返回的数据
								const responseData = typeof res.data === 'string' ? JSON.parse(res
									.data) : res.data;
								console.log(responseData);
								// 检查响应状态
								if (responseData.code === 200) {
									// 成功获取网络地址
									const imageUrl = responseData.url;
									resolve(imageUrl);
								} else {
									// 业务逻辑错误
									reject(new Error(responseData.msg || '上传失败'));
								}
							} catch (error) {
								console.error('响应数据解析失败:', error);
								reject(new Error('服务器响应格式错误'));
							}
						},
						fail: (err) => {
							// 网络请求失败
							// 根据错误类型提供更具体的错误信息
							if (err.errMsg && err.errMsg.includes('request:fail')) {
								reject(new Error('网络连接失败，请检查网络设置'));
							} else {
								reject(new Error('网络请求失败'));
							}
						}
					});
				});
				// 通过上传到七牛云接受返回的url
				// return new Promise((resolve, reject) => {
				// 	uni.uploadFile({
				// 		url: this.$store.state.qiNiuUploadUrl,
				// 		filePath: fileUrl,
				// 		name: "file",
				// 		formData: {
				// 			token: this.uploadToken,
				// 			key: this.uploadKey
				// 		},
				// 		success: (res) => {
				// 			try {
				// 				const data = JSON.parse(res.data);
				// 				resolve(`${this.$store.state.ossBaseUrl}/${data.key}`);
				// 			} catch (e) {
				// 				reject(new Error('Upload response parsing error'));
				// 			}
				// 		},
				// 		fail: reject
				// 	});
				// });
			},
			deletePic(event) {
				this.fileList.splice(event.index, 1);
				if (this.fileList.length === 0) this.acceptType = 'none';
			},
			deleteVideo() {
				this.videoList = [];
				this.acceptType = 'none';
			},

			onPlace() {
			  uni.chooseLocation({
			    success: res => {
			      const address = res.address || '';
			      let province = '';
			      let city = '';
			      let district = '';
			      let detailedAddress = address;
			
			      // 解析省市区信息
			      if (address) {
			        // 特殊处理直辖市（上海市、北京市、天津市、重庆市）
			        const directCities = ['上海市', '北京市', '天津市', '重庆市'];
			        const directCityMatch = address.match(/^(上海市|北京市|天津市|重庆市)/);
			        
			        if (directCityMatch) {
			          // 直辖市情况
			          city = directCityMatch[1];
			          detailedAddress = address.substring(city.length);
			          
			          // 匹配区/县（在直辖市之后的部分中查找区/县）
			          const districtMatch = detailedAddress.match(/^(.+?[区县市])/);
			          if (districtMatch) {
			            district = districtMatch[1];
			            detailedAddress = detailedAddress.substring(district.length);
			          }
			        } else {
			          // 普通省份情况
			          // 匹配省（以省结尾的词）
			          const provinceMatch = address.match(/^(.+?[省市]|.+?自治区|.+?特别行政区)/);
			          if (provinceMatch) {
			            province = provinceMatch[1];
			            detailedAddress = address.substring(province.length);
			          }
			
			          // 匹配市（在省之后的部分中查找市）
			          if (province) {
			            const cityMatch = detailedAddress.match(/^(.+?[市州]|.+?地区)/);
			            if (cityMatch) {
			              city = cityMatch[1];
			              detailedAddress = detailedAddress.substring(city.length);
			            }
			          }
			
			          // 匹配区/县（在市之后的部分中查找区/县）
			          const districtMatch = detailedAddress.match(/^(.+?[区县市])/);
			          if (districtMatch) {
			            district = districtMatch[1];
			            detailedAddress = detailedAddress.substring(district.length);
			          }
			        }
			      }
			
			      this.locationInfo = {
			        name: res.name || district || city || '未知地点',
			        address: detailedAddress.trim() || '未知地址',
			        latitude: res.latitude,
			        longitude: res.longitude,
			        province: province,
			        city: city,
			      };
			    },
			  });
			},
			openTagPopup() {
				this.showTagPopup = true;
			},
			navigateToSelectTopic() {
				// 跳转到新的话题选择页面
				uni.navigateTo({
					url: '/pages_sub/common/topic-select/topic-select', // 新页面的路径
					events: {
						// 监听新页面回传数据的事件
						acceptDataFromTopicSelectPage: (data) => {
							console.log('从话题页返回的数据:', data);
							if (data && data.selectedTags) {
								this.selectedTags = data.selectedTags;
							}
						}
					},
					success: (res) => {
						// 成功跳转后，通过 eventChannel 向新页面传递当前已选的话题
						res.eventChannel.emit('sendInitialData', {
							initialSelectedTags: this.selectedTags
						});
					}
				});
			},
			isTagSelected(topicId) {
				return this.selectedTags.some(tag => tag.topicId === topicId);
			},
			toggleTag(tag) {
				const index = this.selectedTags.findIndex(t => t.topicId === tag.topicId);
				if (index > -1) {
					this.selectedTags.splice(index, 1);
				} else {
					this.selectedTags.push(tag);
				}
			},
			removeTag(index) {
				this.selectedTags.splice(index, 1);
			},
			onConfirmPower(e) {
				this.powerObject = e.value[0];
				this.showPowerPicker = false;
			},
			saveDraft() {
				uni.showToast({
					title: '草稿已保存',
					icon: 'success'
				});
			},
			async publish() {
				if (!this.title.trim()) {
					uni.showToast({
						title: '请填写标题',
						icon: 'none'
					});
					return;
				}
				if (!this.content.trim() && this.fileList.length === 0 && this.videoList.length === 0) {
					uni.showToast({
						title: '请填写内容或上传媒体',
						icon: 'none'
					});
					return;
				}
				this.isSubmitting = true;
				const files = this.acceptType === 'image' ? this.fileList : this.videoList;
				const filesToSubmit = files.filter(f => f.status === 'success').map(f => ({
					fileUrl: f.url,
					isImage: f.isImage,
					fileName: f.originalName
				}));
				const params = {
					title: this.title,
					content: this.content,
					files: filesToSubmit,
					userId: this.$store.state.userInfo.userId,
					categoryId: 4,
					isHomePage: 0,
					isGood: 1,
					location: this.formatLocationInfo(this.locationInfo),
					longitude: this.locationInfo?.longitude,
					latitude: this.locationInfo?.latitude,
					visibility: this.powerObject.id,
					topicIds: this.selectedTags.map(tag => tag.topicId),
				};
				try {
					const res = await publishPost(params);
					if (res.data && (res.data.code === 200 || !res.data.code)) {
						uni.showToast({
							title: '发布成功',
							icon: 'success'
						});
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/index/index'
							});
						}, 1500);
					} else {
						throw new Error(res.data.msg || '发布失败');
					}
				} catch (error) {
					uni.showToast({
						title: error.message,
						icon: 'none'
					});
				} finally {
					this.isSubmitting = false;
				}
			},
			formatLocationInfo(locationInfo) {
				if (!locationInfo) return null;
				// 优先使用完整的省-市-地点格式
				if (locationInfo.province && locationInfo.city && locationInfo.address) {
					return `${locationInfo.province}-${locationInfo.city}-${locationInfo.address}`;
				} else if (locationInfo.city && locationInfo.address) {
					return `${locationInfo.city}-${locationInfo.address}`;
				} else if (locationInfo.address) {
					return `${locationInfo.address}`;
				}

				// 如果连地点名称都没有，返回null
				return null;
			}
		}
	};
</script>

<style lang="scss" scoped>
	.publish-container {
		height: calc(100vh - 88rpx);
		display: flex;
		flex-direction: column;
		background-color: #ffffff;
	}

	.scroll-view-content {
		flex: 1;
		padding: 20rpx 30rpx;
		box-sizing: border-box;
	}

	.title-input-wrapper {
		display: flex;
		align-items: center;
		padding: 10rpx 0;
		border-bottom: 1rpx solid #f0f0f0;

		.title-input {
			flex: 1;
			font-size: 32rpx;
			font-weight: bold;
			height: 80rpx;
		}

		.char-counter {
			font-size: 24rpx;
			color: #c0c4cc;
		}
	}

	.content-textarea-wrapper {
		margin-top: 20rpx;

		.content-textarea {
			width: 100%;
			font-size: 28rpx;
			line-height: 1.6;
			min-height: 200rpx;
		}
	}

	.media-upload-wrapper {
		margin-top: 20rpx;
	}

	.upload-placeholder {
		width: 160rpx;
		height: 160rpx;
		background-color: #f8f8f8;
		border: 1rpx solid #f8f8f8;
		border-radius: 20rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.placeholder-text {
			font-size: 24rpx;
			color: #999;
			margin-top: 8rpx;
		}
	}

	.video-preview-container {
		position: relative;
		width: 200rpx;
		height: 200rpx;

		.video-preview {
			width: 100%;
			height: 100%;
			border-radius: 8rpx;
		}

		.delete-video-icon {
			position: absolute;
			top: -10rpx;
			right: -10rpx;
			background-color: rgba(0, 0, 0, 0.5);
			width: 40rpx;
			height: 40rpx;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}

	.options-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;

		.option-item {
			display: flex;
			align-items: center;
			font-size: 26rpx;
			color: #8F8F8F;
			background-color: #F5F5F5;
			padding: 10rpx 20rpx;
			border-radius: 30rpx;
			margin-right: 20rpx;

			.option-text {
				margin: 0 8rpx;
			}

			.location-text {
				max-width: 200rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}

		.option-item-none {
			background: none !important;
			color: #000 !important;
			font-size: 28rpx !important;
		}
	}

	.selected-tags-container {
		margin-top: 20rpx;
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;

		.tag-wrapper {
			::v-deep .u-tag__text {
				font-weight: 500;
			}
		}
	}

	.bottom-bar {
		position: fixed;
		bottom: 0;
		width: calc(100% - 60rpx);
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #fff;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));

		.draft-button {
			width: 200rpx;
			margin-right: 20rpx;
		}

		.publish-button {
			flex: 1;
			color: #333;
			font-weight: bold;
		}
	}

	.tag-popup {
		padding: 30rpx;

		.popup-header {
			font-size: 32rpx;
			font-weight: bold;
			text-align: center;
			margin-bottom: 30rpx;
		}

		.tag-scroll {
			max-height: 50vh;
		}

		.tag-list {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;
		}

		.popup-footer {
			margin-top: 40rpx;
		}
	}
</style>